package com.mystudy.management.usermanagement.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.mystudy.management.usermanagement.dao.pojo.Admin;
import com.mystudy.management.usermanagement.entity.LoginMessageContainer;
import com.mystudy.management.usermanagement.laytablemessageconvert.LayuiSelectMessageConvert;
import com.mystudy.management.usermanagement.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;


@Controller
public class LoginController {

    //注入请求解析器
    @Autowired
    private LayuiSelectMessageConvert messageConvert;

    //登录服务
    @Autowired
    private LoginService service;

    //验证码服务
    @Autowired
    private Producer kaptchaProducer;


    @RequestMapping("/")
    public String toLoginPage(){
        return "redirect:/admin";
    }

    @RequestMapping("/admin")
    public String loadLoginPage(){
        if(StpUtil.isLogin()){
            return "redirect:/admin/index";
        }
        return "login";
    }


    //处理登录请求
    @PostMapping("/admin/login")
    @ResponseBody
    public JSONObject logCheck(@RequestBody JSONObject loginRequest,HttpSession session){
        JSONObject response = new JSONObject();
        response.put("code",-1);
        LoginMessageContainer loginMessageContainer = messageConvert.loginRequestFirstStepMessageConverter(loginRequest,(String) session.getAttribute("kaptchaText"));
        //验证码不对直接返回响应
        if(!loginMessageContainer.isKaptchaCheck()){
            response.put("code",0);
            return response;
        }
        //登录令牌查询
        if(service.messageCheck(loginMessageContainer.getAdmin(),loginMessageContainer.isRememberChoice())){
            response.put("code",1);
        }

        return response;

    }


    //验证码请求
    @RequestMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入session
        session.setAttribute("kaptcha", image);
        session.setAttribute("kaptchaText",text);

        //将图片传给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "PNG", os);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
